#!/usr/bin/env python
# -*- coding:utf-8 -*-
#encoding=utf-8
'''
Created on 2013年12月16日

@author: daimin
'''

import model
import act_cls
import logfmt
import sdk_dbutil
import comm
import datetime

class SDKLog(model.Model):
    def __init__(self, **kwargs):
        model.Model.__init__(self, **kwargs)
        self.__gameid   = self._logkey
        self.sdk_userinfo_dbutil    = sdk_dbutil.SdkUserInfo(cfg=self._modcfg, gameid=self.__gameid)
        self.sdk_payinfo_dbutil     = sdk_dbutil.SdkPayInfo(cfg=self._modcfg, gameid=self.__gameid)
        self._alter_clear           = False   
        
        self.__gamedata_interface   = GameDataSdkInterface(
                                                          model    = self,
                                                          data     = self._gdata[GameDataSdkInterface.NAME],
                                                          pasday   = self._pasday,
                                                          gameid   = self.__gameid,
                                                          cfg      = self._gamecfg['interfaces'][GameDataSdkInterface.NAME],
                                                          )
        
        
    def _item_call(self, line):
        """单调调用处理回调函数
        """
        obj  = act_cls.Act.genParsedObj(line, self._pasday, self._gamecfg['log_split'])
        self.__gamedata_interface.get_cur_key(obj)
                
        if obj.TAG == logfmt.SDK_REG:
            self.get_new_user(obj)
        elif obj.TAG == logfmt.SDK_LOGIN:
            self.__gamedata_interface.update_log_user(obj)
        elif obj.TAG == logfmt.SDK_PAY:
            self.__gamedata_interface.update_pay_user(obj)
            
    def _count_call(self, data):
        """统计分析回调处理函数
        """
        self.__gamedata_interface.countdata(data)
        
    
    def _request(self):
        self.sdk_userinfo_dbutil._save()
        self.__gamedata_interface.request()
            
            
class GameDataSdkInterface(model.Interface):
    """游戏平台接口数据处理
    """
    NAME  = "gamedatasdk"
    
    def __init__(self, **kwargs):
        model.Interface.__init__(self, **kwargs)
        self.__pasday   = kwargs['pasday'] if 'pasday' in kwargs else None
        self.__yesregusers = {}
        self.__yesday = self.__pasday - datetime.timedelta(1)
        
    
    def __get_channel_rename(self, chlnum):
        return self._model._gamecfg['channels'][chlnum]\
             if chlnum in self._model._gamecfg['channels'] else ''
    
    
    def get_new_user(self, pobj):
        """获取新注册用户
        """
        self.__do_with_reguser(pobj)
        self._curitem['__regusers'][pobj.userName] = pobj.channel

    def __do_with_reguser(self, pobj):
        ### 插入新注册用户
        self._model.sdk_userinfo_dbutil.add_new_user(
                                                           uname     = pobj.userName,
                                                           gameid    = pobj.gameid,
                                                           channel   = pobj.channel,
                                                           os        = pobj.os,
                                                           svrid     = pobj.server,
                                                           regip     = comm.ip2long(pobj.ip),
                                                           type      = pobj.userType,
                                                           regtime   = comm.datetime2timestamp(pobj.time)
                                                          )
        if pobj.userType == 0:
            ### 新增用户
            self._curitem['newreg'] += 1
        else:
            ### 新增未注册用户
            self._curitem['notreg'] += 1
            
        
    def __do_with_loguser(self, pobj):
        ### 插入新注册用户
        if self._model.sdk_userinfo_dbutil.is_new_user(pobj.gameid, pobj.userName):
            self.__do_with_reguser(pobj)
            self._curitem['__regusers'][pobj.userName] = pobj.channel
        else:
            ### 更新登陆用户信息
            self._model.sdk_userinfo_dbutil.update_user_info(
                                                           uname     = pobj.userName,
                                                           gameid    = pobj.gameid,
                                                           svrid     = pobj.server,
                                                           os        = pobj.os,
                                                           lastip    = comm.ip2long(pobj.ip),
                                                           logintime = int(comm.datetime2timestamp(pobj.time)),
                                                           channel   = pobj.channel,
                                                           )

    def __get_lastregusers(self, keys):
        ### 得到昨天注册的所用用户
        if self.__yesregusers is {} or keys not in self.__yesregusers:
            yesreguser = self._model.sdk_userinfo_dbutil.get_users_date(self.__yesday, keys[0])
            if yesreguser is not None:
                for yuser in yesreguser:
                    uyuser = comm.unserialize(yuser)
                    if uyuser is not None:
                        iuyuser = dict(uyuser)
                        tkeys = (keys[0], iuyuser.get('os', None), iuyuser.get('channel', None), iuyuser.get('svrid', None))
                        if tkeys in self.__yesregusers:
                            self.__yesregusers[iuyuser['uname']] = 1
                        try:
                            self.__yesregusers = {iuyuser['uname'] : 1}
                        except:
                            pass
                        
        
        return self.__yesregusers.get(keys, {})
    
    def get_cur_key(self, pobj):
        ### 第一次登陆用户就是注册用户
        def callback_key(key):
            self._data[key] = dict([(p, 0) for p in self._interface_cfg['params']['items']])
            self._data[key]['__regusers'] = {}
            self._data[key]['__payusers'] = {}
            self._data[key]['__logusers'] = {}
            self._data[key]['__yesregusers'] = self.__get_lastregusers(key)
        self._set_cur_key((pobj.gameid, pobj.os, pobj.channel, pobj.server), callback_key)
        
     
    def update_log_user(self, pobj):
        """更新登陆用户信息
        """
        ### 登入次数
        self._curitem['login_sum'] += 1
                    
        self.__do_with_loguser(pobj)
        self._curitem['__logusers'][pobj.userName] = pobj.channel

            
            
    def update_pay_user(self, pobj):
        ### 新增付费用户
        if self._model.sdk_payinfo_dbutil.is_new_pay(uname = pobj.userName, gameid = pobj.gameid):
            self._curitem['xczrs'] += 1
            
        ### 更新到用户表
        self._model.sdk_payinfo_dbutil.update_pay_user(
                                                  uname   = pobj.userName,
                                                  gameid  = pobj.gameid,
                                                  paytime = int(comm.datetime2timestamp(pobj.time)),
                                                  paynum  = '+1',
                                                  )
        
        self._curitem['czje']      += int(pobj.price)
        self._curitem['czbs']      += 1
        self._curitem['__payusers'][pobj.userName] = pobj.channel
            
            
    def countdata(self, data):
        for key in self._data.keys():
            ### 登陆用户
            self._data[key]['loginnum']      += len(self._data[key]['__logusers'])
            ### 新登陆用户
            self._data[key]['loginnum_new']  += len(self._data[key]['__regusers'])
            ### 活跃用户
            self._data[key]['user_hy']       += len(self._data[key]['__logusers'])
            ### 充值人数
            self._data[key]['czrs']          += len(self._data[key]['__payusers'])
            ### 前一天新登入
            self._data[key]['qytxdryh']      += len(self._data[key]['__yesregusers'])

            for uname in self._data[key]['__regusers']:
                ### 新注册付费
                if uname in self._data[key]['__payusers']:
                    self._data[key]['xzcffyh'] += 1
                ### 前一天新登入，今天还登入
                if uname in self._data[key]['__yesregusers']:
                    self._data[key]['qytxdryhjthdl'] += 1
                    
                    
    def request(self):
        pasday = comm.datetime2timestamp2(self.__pasday)
        for (key, items) in self._data.items():
            params = dict(zip(self._interface_cfg['params']['keys'], [''] * len(self._interface_cfg['params']['keys'])) +\
                          zip(self._interface_cfg['params']['items'], [''] * len(self._interface_cfg['params']['items'])))
            
            params = dict(map(lambda x:(x[0], items.get(x[0], '')), params.items()))
            
            (params['cgame'], params['cdevice'], params['cchannel'],params['cserver'], params['cdate'], params['cperiod'])   =\
                                                                                                      key + (str(pasday), 'd')
            self._model.req_params.append((GameDataSdkInterface.NAME, params))
            
                    
        